var kendoUtils = function () {
    //kendo界面元素绑定对象
    this.mvvmModel;
    //构造绑定界面元素对象
    this.bindBaseModel;
    //kendoGrid控件对象DIV ID集合
    this.gridList;
    //kendoWindow控件对象集合
    this.windowList;
    //kendoChart报表对象集合
    this.kendoChartList;
    //绑定的页面对象
    this.targetObj;
    this.init();
    return this;
};

kendoUtils.prototype = {
    init: function () {
        this.initDatepicker();
//			x18n.on(['lang:change', 'dict:change'],this.changeLanguages,null,this);
    },
    //根据JSON对象赋予绑定字段值
    setBindFieldValue: function (jsonObj, nullIsSet) {
        for (var names in jsonObj) {
            if (isNotEmpt(jsonObj[names]) || true == nullIsSet) {
                this.mvvmModel.set(names, $.trim(jsonObj[names]));
            }
        }
    },//根据变种JSON对象赋予绑定字段值
    setVariantBindFieldValue: function (jsonObj, nullIsSet) {
        var array = new Array();
        for (var names in jsonObj) {
            if (isNotEmpt(jsonObj[names]) || true == nullIsSet) {
                if (typeof jsonObj[names] === 'object') {
                    this.foreachJson(jsonObj[names], array, names);
                    var l = array.length;
                    for (var i = 0; i < l; i++) {
                        var arr = array[i].split('_');
                        var value = jsonObj;
                        for (var j = 0; j < arr.length; j++) {
                            value = value[arr[j]];
                        }
                        this.mvvmModel.set(array[i], $.trim(value.toString()));
                    }
                }
                this.mvvmModel.set(names, $.trim(jsonObj[names]));
            }
        }
    },
    //根据对象属性名把对应的界面元素值职空
    setBindFieldNull: function (objArray) {
        for (var i = 0; i < objArray.length; i++) {
            this.mvvmModel.set(objArray[i].fieldName, "");
        }
    },
    //遍历json节点,获取节点路径数组
    foreachJson: function (jsonObj, array, name) {
        for (var o in jsonObj) {
            if (typeof jsonObj[o] === 'object') {
                this.foreachJson(jsonObj[o], array, name + '_' + o);
            } else {
                array.push(name + '_' + o);
            }
        }
    },
    //获取指定元素中所有绑定的静态元素对象
    getBindTitleArray: function (targetObj) {
        if (!targetObj) return;
        var textArray = targetObj.find("*[data-bind *= 'text']");
        var array = new Array();
        this.getBindArrayObj(textArray, array, "text");
        return array;
    },
    //获取指定元素中所有绑定的动态元素对象
    getBindFieldArray: function (targetObj) {
        if (!targetObj) return;
        var fieldArray = targetObj.find("*[data-bind *= 'value']");
        ;
        var array = new Array();
        this.getBindArrayObj(fieldArray, array, "value");
        return array;
    },
    //获取绑定数据元素对象
    getBindArrayObj: function (docArray, objArray, type) {
        for (var i = 0; i < docArray.length; i++) {
            //界面元素绑定属性
            var data_bind = $(docArray[i]).attr("data-bind");
            var tIndexOf = data_bind.indexOf(type);
            var data_bindSub = data_bind.substring(tIndexOf, data_bind.length);
            var indexOf = data_bindSub.indexOf(",");
            var titleName = data_bindSub.substring(0, indexOf == -1 ? data_bindSub.length : indexOf).split(":");
            if (type == "text") {
                objArray.push({titleName: ITS.trim(titleName[1]), defaultValue: $(docArray[i]).val()});
            } else if (type == "value") {
                objArray.push({fieldName: ITS.trim(titleName[1]), defaultValue: $(docArray[i]).val()});
            }

        }
    },
    //初始化页面所有input属性包含bdPicker的控件
    initDatepicker: function () {
        var that = this;
        //只有年月
        $("input[monthpicker]").each(function () {
            try {
                var paramet = $(this).attr("monthpicker");
                if (isEmpty(paramet)) {
                    paramet = "format : 'yyyy-MM',start : 'year',depth : 'year',dateInput : false";
                } else {
                    if (paramet.indexOf("format") < 0) {
                        paramet += ",format : 'yyyy-MM'";
                    }
                    if (paramet.indexOf("start") < 0) {
                        paramet += ",start : 'year'";
                    }
                    if (paramet.indexOf("depth") < 0) {
                        paramet += ",depth : 'year'";
                    }
                    if (paramet.indexOf("dateInput") < 0) {
                        paramet += ",dateInput : false";
                    }
                }
                paramet += ",culture:'" + x18n.chosenLocal + "'";
                var pickerJson = eval("({" + paramet + "})");
                $(this).kendoDatePicker(pickerJson);
                $(this).removeAttr("monthpicker");
                that.bdPickerChange($(this), "kendoDatePicker");
            } catch (e) {
            }
        });
        //只有日期
        $("input[bdPicker]").each(function () {
            try {
                var paramet = $(this).attr("bdPicker");
                if (isEmpty(paramet)) {
                    paramet = "format : 'yyyy-MM-dd'";
                } else {
                    if (paramet.indexOf("format") < 0) {
                        paramet += ",format : 'yyyy-MM-dd'";
                    }
                }
                paramet += ",culture:'" + x18n.chosenLocal + "'";
                var pickerJson = eval("({" + paramet + "})");
                $(this).kendoDatePicker(pickerJson);
                $(this).removeAttr("bdPicker");
                that.bdPickerChange($(this), "kendoDatePicker");
            } catch (e) {
            }
        });
        //只有时间
        $("input[timePicker]").each(function () {
            try {
                var paramet = $(this).attr("timePicker");
                if (isEmpty(paramet)) {
                    paramet = "format : 'HH:mm',parseFormats:['HH:mm']";
                } else {
                    if (paramet.indexOf("format") < 0) {
                        paramet += ",format : 'HH:mm'";
                    }
                    if (paramet.indexOf("parseFormats") < 0) {
                        paramet += ",parseFormats:['HH:mm']";
                    }
                }
                paramet += ",culture:'" + x18n.chosenLocal + "'";
                var pickerJson = eval("({" + paramet + "})");
                pickerJson["interval"] = 1;  //设置为选择间隔为1分钟
                $(this).kendoTimePicker(pickerJson);
                $(this).removeAttr("timePicker");
                that.bdPickerChange($(this), "kendoTimePicker");
            } catch (e) {
            }
        });
        //日期和时间都有
        $("input[bdDataTimePicker]").each(function () {
            try {
                var paramet = $(this).attr("bdDataTimePicker");
                if (isEmpty(paramet)) {
                    paramet = "format : 'yyyy-MM-dd HH:mm:ss'";
                } else {
                    if (paramet.indexOf("format") < 0) {
                        paramet += ",format : 'yyyy-MM-dd HH:mm:ss'";
                    }
                }
                paramet += ",culture:'" + x18n.chosenLocal + "'";
                var pickerJson = eval("({" + paramet + "})");
                pickerJson["interval"] = 1;  //设置为选择间隔为1分钟
                $(this).kendoDateTimePicker(pickerJson);
                $(this).removeAttr("bdDataTimePicker");
                that.bdPickerChange($(this), "kendoDateTimePicker");
            } catch (e) {
            }
        });
        kendo.culture(x18n.chosenLocal);
    },
    //change事件
    bdPickerChange: function (picker, type) {
        var minDate = picker.attr("minDate");
        var maxDate = picker.attr("maxDate");
        var targetObj = null;
        if (isEmpty(picker.attr("parentDiv"))) {
            targetObj = picker.parents("div");
        } else {
            targetObj = $("#" + picker.attr("parentDiv"));
        }
        picker.attr("readonly", "readonly");
        picker.bind("change", picker, function () {  //添加change事件
//				var pattern="(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";
            var dataValue = $(this).val();
//				if(dataValue.match(pattern) == null){
//				dataValue="";
//				$(this).val("");
//				}
            if (isNotEmpt(minDate)) {
                var mins = isEmpty(dataValue) ? "1900-01-01 00:00:00" : dataValue;
                targetObj.find("#" + minDate).data(type).setOptions({
                    min: new Date(mins.replaceAll("-", "/"))
                });
            }
            if (isNotEmpt(maxDate)) {
                var maxs = isEmpty(dataValue) ? "2099-12-30 00:00:00" : dataValue;
                targetObj.find("#" + maxDate).data(type).setOptions({
                    max: new Date(maxs.replaceAll("-", "/"))
                });
            }
        });
    },
    //打开一个window窗口
    openWindow: function (targetObj, options, isDestroy) {
        targetObj = $("#" + targetObj);
        if (!options) return;
        if (!this.bindBaseModel.bindx18nObjName) return;
        var kendoWindows = $(targetObj).data("kendoWindow");
        if (kendoWindows && !isDestroy) {
            kendoWindows.open();
            return targetObj.attr("id");
        } else if (kendoWindows && isDestroy) {
            kendoWindows.destroy();
        }
        if (!options.x18nTitle) {
            options.x18nTitle = options.title;
        }
        options.title = t(this.bindBaseModel.bindx18nObjName + "." + options.x18nTitle);
        if (!options.title)
            options.title = options.x18nTitle;
        if (!this.windowList) this.windowList = new Array();
        var a = Math.round(Math.random() * 100000);
        var window = $("<div id='" + a + "'/>");
        this.targetObj.prepend(window);
        options.modal = true;
        options.pinned = true;
        options.draggable = false;
        if (isEmpty(options.close)) {
            options.close = function (e) {
                this.destroy();
            };
        }
        var content = options["content"];
        options["content"] = "";
        //打开窗口时检测是否加载到了登录界面
        var customOpen = options.open;
        options.open = function (e) {
            $("#" + a).load(baseSitePath + content, function () {
                if ($("#" + a).find("#loginBgDiv").length > 0) {  //表示没有加载到html或者加载到登录页面，则跳转到登录页面
                    $("#" + a).empty();
                    loginTimeOut();
                    return;
                }
                //否则表示加载成功，那么执行用户自定义open方法
                if (isNotEmpt(customOpen) && typeof customOpen == "function") {
                    customOpen(e);
                }
            })
        }
        window.kendoWindow(options);
        kendoWindows = window.data("kendoWindow");
        kendoWindows.center();
        this.windowList.push(kendoWindows);
        $("#" + a).attr("kdSingle", true);
        $("#" + a).parent().css("z-index", 9000);
        $("div[class='k-overlay']").css("z-index", 8999);
        $("div[class='k-overlay']").append("<iframe style='width:100%;height:100%;'></iframe>");
        return a;
    },
    //获取绑定字段JSON对象
    getBindDocJson: function (obj) {
        if (!this.bindBaseModel || !this.mvvmModel) return;
        var bindFieldArray = obj;
        var object = new Object();
        if (!bindFieldArray) {
            bindFieldArray = this.bindBaseModel.bindFieldArray;
        }
        if (!bindFieldArray) return;
        for (var i = 0; i < bindFieldArray.length; i++) {
            var fieldName = bindFieldArray[i].fieldName;
            var fieldValue = this.mvvmModel.get(fieldName);
            object[fieldName] = isEffective(fieldValue);
        }
        return object;
    },
    //递归绑定动态元素
    recursiveBindDoc: function (array, mvvmObj) {
        if (array.constructor == Array) {
            for (var i = 0; i < array.length; i++) {
                var field = array[i];
                if (field.constructor == Array) {
                    this.recursiveBindDoc(field, mvvmObj);
                } else if (field.constructor == Object) {
                    if (field.detail) {
                        this.recursiveBindDoc(field.detail, mvvmObj);
                    } else {
                        var fieldName = array[i].fieldName;
                        var defaultValue = array[i].defaultValue;
                        if (!defaultValue) defaultValue = "";
                        mvvmObj[fieldName] = defaultValue;
                    }
                }
            }
        } else if (array.constructor == Object) {
            if (array.detail) {
                this.recursiveBindDoc(array.detail, mvvmObj);
            } else {
                var fieldName = array.fieldName;
                var defaultValue = array.defaultValue;
                if (!defaultValue) defaultValue = "";
                mvvmObj[fieldName] = defaultValue;
            }
        }
    },
    //重置DIV大小为当前页面大小
    resetDviSize: function (targetObj) {
        var LeftCont = targetObj.parents(".content");
        targetObj.height(LeftCont.height());
        targetObj.width(LeftCont.width());
    },
    //绑定界面元素
    bindDoucment: function (bindBaseModel, targetObj, targetJs) {
        this.resetDviSize(targetObj);
        if (!bindBaseModel || !targetObj) return;
        try {
            var bindTitleArray = bindBaseModel.bindTitleArray;
            var bindFieldArray = bindBaseModel.bindFieldArray;
            var bindFunctionArray = bindBaseModel.bindFunctionArray;
            var mvvmObj = new Object();
            if (bindTitleArray) {
                var bindx18nObjName = bindBaseModel.bindx18nObjName;
                for (var i = 0; i < bindTitleArray.length; i++) {  //循环取出静态绑定元素(span，lable等标签固定文本)
                    var titleName = bindTitleArray[i].titleName;
                    var x18nName = bindTitleArray[i].x18nName;
                    if (!x18nName) x18nName = titleName;
                    mvvmObj[titleName] = t(bindx18nObjName + "." + x18nName);
                }
            }
            if (bindFieldArray) {   //绑定动态数据，如输入框等
                for (var field in bindFieldArray) {
                    this.recursiveBindDoc(bindFieldArray[field], mvvmObj);
                }
            }
            if (bindFunctionArray) {  //绑定方法
                for (var i = 0; i < bindFunctionArray.length; i++) {
                    var functionName = bindFunctionArray[i].fName;
                    var functions = bindFunctionArray[i].fs;
                    mvvmObj[functionName] = functions;
                    targetObj.find("*[data-bind*='" + functionName + "']").data("that", targetJs);
                }
            }
        } catch (e) {
        }
        this.mvvmModel = kendo.observable(mvvmObj);
        this.bindBaseModel = bindBaseModel;
        this.targetObj = targetObj;
        kendo.bind(targetObj, this.mvvmModel);
        return this.mvvmModel;
    },
    //查询数据源
    queryGridDate: function (gridId) {
        if (!this.mvvmModel || !this.bindBaseModel || !gridId) return;
        var grid = this.targetObj.find("#" + gridId).data("kendoGrid");
        var bindFieldArray = this.bindBaseModel.bindFieldArray; //查询字段
        var queryModel = new Object();
        //如果没有query对象直接取所有的
        var query = bindFieldArray.query ? bindFieldArray.query : bindFieldArray;
        for (var i = 0; i < query.length; i++) {
            var fieldName = query[i].fieldName;
            queryModel[fieldName] = isEffective(this.mvvmModel.get(fieldName));
        }
        var data = {queryJson: JSON.stringify(queryModel), optype: "query"};
        var url = grid.options.dataSource.options.transport.read.url;
        var type = grid.options.dataSource.options.type;
        var fields = grid.options.dataSource.options.schema.model.fields;
        var dataSource = this.getDataSource({url: url, data: data, dataType: type, field: fields});
        grid.setDataSource(dataSource);
    },
    //查询数据源
    queryGridDateByData: function (gridId, data) {
        if (!this.mvvmModel || !this.bindBaseModel || !gridId || !data) return;
        var grid = this.targetObj.find("#" + gridId).data("kendoGrid");
        var data = data;
        var url = grid.options.dataSource.options.transport.read.url;
        var type = grid.options.dataSource.options.type;
        var fields = grid.options.dataSource.options.schema.model.fields;
        var dataSource = this.getDataSource({url: url, data: data, dataType: type, field: fields});
        grid.setDataSource(dataSource);
    },
    //设置grid本地数据源
    setGridLocaData: function (gridId, datas) {
        if (!gridId || !this.targetObj) return;
        var grid = this.targetObj.find("#" + gridId).data("kendoGrid");

        var schemaObj = grid.options.dataSource.schema;
        if (isNotEmpt(grid.options.dataSource.options)) schemaObj = grid.options.dataSource.options.schema;
        if (isEmpty(schemaObj)) {
            schemaObj = {
                model: {
                    fields: grid.options.dataSource.fields
                }
            };
        }
        var dataSource = new kendo.data.HierarchicalDataSource({
            data: datas,
            schema: schemaObj
        });
        grid.setDataSource(dataSource);
    },
    //创建grid列表
    createGird: function (targetObj, gridObj) {
        if (!targetObj || !gridObj) return;
        if (!this.bindBaseModel.bindx18nObjName) return;
        var bindx18nObjName = this.bindBaseModel.bindx18nObjName;
        var dataSourceOptions = gridObj.dataSource;
        var columns = gridObj.columns;
        if (!columns) return;
        var dataSource = null;
        if (dataSourceOptions) {
            if (dataSourceOptions.url) {
                dataSource = this.getDataSource(dataSourceOptions);
            } else {
                dataSource = dataSourceOptions;
            }
        }
        var gridColumns = this.getGridColumns(columns, bindx18nObjName);
        var toolBar = this.getToolBar(gridObj.toolbar, bindx18nObjName);
        gridObj.dataSource = dataSource;
        gridObj.columns = gridColumns;
        gridObj.toolbar = toolBar;
        if (!isEmptyObject(gridObj.pageable) || gridObj.pageable == true) {
            gridObj.pageable = {};
            gridObj.pageable.messages = {
                display: t("sysX18n.display"),
                empty: t("sysX18n.empty"),
                page: t("sysX18n.page"),
                of: t("sysX18n.of"),
                itemsPerPage: t("sysX18n.itemsPerPage"),
                first: t("sysX18n.first"),
                previous: t("sysX18n.previous"),
                next: t("sysX18n.next"),
                last: t("sysX18n.last"),
                refresh: t("sysX18n.refresh")
            };
        }
        if (isNotEmpt(gridObj.columnMenu)) {
            gridObj.columnMenu = {
                messages: {
                    sortAscending: t("sysX18n.sortAscending"),
                    sortDescending: t("sysX18n.sortDescending"),
                    filter: t("sysX18n.filter"),
                    columns: t("sysX18n.columns")
                }
            };
        }
        if (!this.gridList) this.gridList = new Array();
        $(targetObj).kendoGrid(gridObj);
        this.gridList.push($(targetObj).attr("id"));
    },
    getToolBar: function (toolbar) {  //国际化表头按钮
        if (!toolbar || !this.bindBaseModel.bindx18nObjName) return;
        for (var i = 0; i < toolbar.length; i++) {
            if (!toolbar[i].x18Name)
                toolbar[i].x18Name = toolbar[i].text;
            toolbar[i].text = t(this.bindBaseModel.bindx18nObjName + "." + toolbar[i].x18Name);
            if (!toolbar[i].text)
                toolbar[i].text = toolbar[i].x18Name;
        }
        return toolbar;
    },
    getGridColumns: function (gridHead) {   //获取grid表头对象
        if (!gridHead || !this.bindBaseModel.bindx18nObjName) return;
        for (var i = 0; i < gridHead.length; i++) {
            if (!gridHead[i].title) {
                gridHead[i].title = t(this.bindBaseModel.bindx18nObjName + "." + gridHead[i].field);
            } else {
                var title = t(this.bindBaseModel.bindx18nObjName + "." + gridHead[i].title);
                if (title) gridHead[i].title = title;
            }
            if (gridHead[i].command) {
                for (var j = 0; j < gridHead[i].command.length; j++) {
                    gridHead[i].command[j].text = t(this.bindBaseModel.bindx18nObjName + "." + gridHead[i].command[j].text);
                }
            }
        }
        return gridHead;
    },
    getDataSource: function (options) {  //获取grid数据源
        if (!options) return;
        if (!options.data) options.data = {};
        return new kendo.data.DataSource({
            type: options.dataType || "jsonp",
            transport: {
                read: {
                    url: options.url,
                    data: options.data
                },
                parameterMap: function (options, operation) {
                    if (operation == "read") {
                        let parameter = {
                            token: options.page,
                        }
                        return parameter;
                    }
                }
            },
            schema: {
                model: {
                    fields: options.field
                },
                data: function (response) {
                    return response.data.list;
                },
                total: function (response) {
                    return response.data.total;
                }
            },
            requestEnd: options.requestEnd,
            pageSize: options.pageSize == undefined ? 20 : options.pageSize,
            serverPaging: true,
            serverFiltering: true,
            serverSorting: true
        });
    },
    x18nGridUI: function (kendoGrid, bindx18nObjName) {  //国际化grid列表
        if (!kendoGrid || !bindx18nObjName) return;
        for (var i = 0; i < kendoGrid.length; i++) {
            var gridDiv = this.targetObj.find("#" + kendoGrid[i]);
            var grid = gridDiv.data("kendoGrid");
            var columns = grid.columns;
            for (var i = 0; i < columns.length; i++) {
                columns[i].title = t(bindx18nObjName + "." + columns[i].field);
            }
            grid.columns = columns;
            grid._thead(true);
            var toolbar = grid.options.toolbar;
            for (var i = 0; i < toolbar.length; i++) {
                toolbar[i].text = t(bindx18nObjName + "." + toolbar[i].x18Name);
            }
            grid._toolbar(gridDiv.find(".k-toolbar"));
        }
    },
    x18nbindDateUI: function (observable, bindBaseModel) { //国际化绑定的静态文本
        if (!observable || !bindBaseModel) return;
        var bindTitleArray = bindBaseModel.bindTitleArray;
        for (var i = 0; i < bindTitleArray.length; i++) {
            var titleName = bindTitleArray[i].titleName;
            var x18nName = bindTitleArray[i].x18nName;
            observable.set(titleName, t(bindBaseModel.bindx18nObjName + "." + x18nName));
        }
    },
    x18nDatepickerUI: function () {  //国际化日期控件
        $("input[data-role='datepicker']").each(function () {
            var dataPicker = $(this).data("kendoDatePicker");
            kendo.culture(x18n.chosenLocal);
            dataPicker.dateView.calendar.element.removeData("dateView");
        });
    },
    x18nWindowUI: function (window, bindx18nObjName) { //国际化window窗口
        if (!window || !bindx18nObjName) return;
        for (var i = 0; i < window.length; i++) {
            var kendoWindow = window[i];
            if (kendoWindow) {
                kendoWindow.title(t(bindx18nObjName + "." + kendoWindow.options.x18nTitle));
                kendoWindow.refresh();
            }
        }
    },
    //当语言切换时，更新界面UI
    changeLanguages: function () {
        this.x18nbindDateUI(this.mvvmModel, this.bindBaseModel);
        this.x18nGridUI(this.gridList, this.bindBaseModel.bindx18nObjName);
        this.x18nWindowUI(this.windowList, this.bindBaseModel.bindx18nObjName);
        this.x18nDatepickerUI();
        this.x18nKendoChart();
    },
    //------------------------------------------自动填充公用代码
    autoCompleteUser: function (field, dataText, selectFun, changeFun) {  //用户信息自动填充
        var autoComplete = this.targetObj.find("#" + field).kendoAutoComplete({
            optionLabel: "请输入关键字...",
            dataTextField: dataText,
            template: "#:userName#(#:userAccount#)",
            filter: "eq",
            ignoreCase: false,
            minLength: 1,
            dataSource: {
                type: "odata",
                serverFiltering: true,
                transport: {
                    read: {
                        url: baseApiPath + "user/autoComplete"
                    }
                }
            }
        }).data("kendoAutoComplete");
        if (!isEmpty(selectFun) && typeof selectFun == "function") {
            autoComplete.bind("select", selectFun);
        }
        if (!isEmpty(changeFun) && typeof changeFun == "function") {
            autoComplete.bind("change", changeFun);
        }
    },
    //生成kendo报表
    createKendoChartUI: function (object, chartJson, type) {
        var kendoChartUIs = new kendoChartUI(object, chartJson, type);
        if (isEmpty(this.kendoChartList))
            this.kendoChartList = new Array();
        this.kendoChartList.push(kendoChartUIs);
        return kendoChartUIs;
    },
    //当语言改变国际化报表控件
    x18nKendoChart: function () {
        if (isEmpty(this.kendoChartList)) return;
        for (var i = 0; i < this.kendoChartList.length; i++) {
            this.kendoChartList[i].x18nKendoChart();
        }
    },

    /**
     * 通过代码设置一次下拉框中的值
     */
    setDropDownListVal: function (elemObj, value) {
        if (isEmpty(value)) return;
        var dataBind = elemObj.attr("data-bind");
        if (isEmpty(dataBind)) return;
        var mvField = dataBind.split(":")[1];
        if (isNotEmpt(mvField)) {
            this.mvvmModel.set(mvField, value);
        }
    }
};


/**
 * 关闭弹出窗口
 */
closeWindow = function () {
    $("div[kdSingle=true]").data("kendoWindow").close();
};

/**
 * 验证目标区域内所有data-bind元素是否验证通过
 */
validityForm = function (targetObj, x18nObj) {
    var flag = true;
    if (typeof (targetObj) != "object") {
        targetObj = $("#" + targetObj);
    }
    targetObj.find("input[data-bind],input[data-validate],select[data-validate]").each(function () {
        if ($(this).attr("disabled") == "disabled") {
            return true;
        }
        if (!this.validity.valid) {
            $(this).addClass('red-textbox');
            var msg = (this.required && this.value == '') ? '请注意,这里不能留空哦~!' : $(this).attr("validationMessage");
            if (targetObj.special) {

                notification({title: '错误', message: $(this).attr("validationMessage")}, 'error')
            } else {
                var downList = $(this).data('kendoDropDownList');
                if (downList) {
                    layer.tips(msg, $(this).parent(), {tipsMore: true, tips: [2, '#78BA32']});
                } else {
                    layer.tips(msg, this, {tipsMore: true, tips: [2, '#78BA32']});
                }
            }

            //notification({ title:"验证失败",message:$(this).attr("validationMessage")},'info');
            //$.messager.alert(t("goableMessage.validityError"),t(x18nObj+"."+$(this).attr("validationMessage")),'info');
            flag = false;
        } else {
            $(this).removeClass('red-textbox');
        }

    });
    return flag;
};


//递归获取选中的选中nodes对象
function queryNodes(treeview, queryArray) {
    var nodes = treeview.dataSource.view();
    var arrayList = new Array();
    checkedNode(treeview, nodes, queryArray);
    return arrayList;
}

function checkedNode(tree, nodes, queryArray, arrayList) {
    for (var i = 0; i < nodes.length; i++) {
        var flag = true;
        var model = $.parseJSON(nodes[i]["model"]);
        for (var j = 0; j < queryArray.length; j++) {
            var queryObj = queryArray[j];
            if (queryObj["value"]) {
                if (!model[queryObj["name"]] && queryObj["value"]) {
                    flag = false;
                } else if (model[queryObj["name"]].toUpperCase().indexOf(queryObj["value"].toUpperCase()) < 0) {
                    flag = false;
                } else if (model[queryObj["name"]].toUpperCase().indexOf(queryObj["value"].toUpperCase()) >= 0) {
                    j = queryArray.length;
                    flag = true;
                }
            }
        }
        var nodeElement = tree.findByUid(nodes[i].uid);
        nodeElement.find("input[type='checkbox']:first")[0].checked = flag;
        if (flag) {
            treeViewExpand(nodeElement, tree);
            arrayList.push(nodeElement);
        }
        if (nodes[i].hasChildren) {
            checkedNode(tree, nodes[i].children.view(), queryArray, arrayList);
        }
    }
}


//展开选中的父级节点
function treeViewExpand(node, tree) {
    var parent = tree.parent(node);
    if (!isEmptyObject(parent[0])) {
        treeViewExpand(parent, tree);
    }
    tree.expand(node);
}

function isEmptyObject(obj) {
    for (var n in obj) {
        return false;
    }
    return true;
}

function getCheckedNode(tree, nodes, checkedNodes) {
    for (var i = 0; i < nodes.length; i++) {
        var nodeElement = tree.findByUid(nodes[i].uid);
        if (nodeElement.find("input[type='checkbox']:first")[0].checked) {
            checkedNodes.push(nodes[i]);
        }
        if (nodes[i].hasChildren) {
            getCheckedNode(tree, nodes[i].children.view(), checkedNodes);
        }
    }
}


function isEmpty(obj) {
    if (undefined == obj || obj.length == 0 || null == obj)
        return true;
    if ("" == ITS.trim(obj))
        return true;
    return false;
}

function isEffective(obj) {
    if (typeof (obj) === "string") {
        if ("" == obj || undefined == obj || obj.length == 0)
            return undefined;
    }
    return obj;
}

function isVariantEmpty(obj) {
    try {
        if (typeof obj != 'undefined') {
            return false;
        }
    } catch (err) {
        return true;
    }
}

function isVariantNotEmpty(obj) {
    try {
        if (typeof obj != 'undefined') {
            return true;
        }
    } catch (err) {
        return false;
    }
}

function isExitsFunction(funcName) {
    try {
        if (typeof (eval(funcName)) == "function") {
            return true;
            //   funcName();
        }
    } catch (e) {
        console.log(eval(funcName) + "+++++++++++++++++我异常了!!!!!!!!");
    }
    return false;
}

//比较日期大小
function compareDate(checkStartDate, checkEndDate) {
    var arys1 = new Array();
    var arys2 = new Array();
    if (checkStartDate != null && checkEndDate != null) {
        arys1 = checkStartDate.split('-');
        var sdate = new Date(arys1[0], parseInt(arys1[1] - 1), arys1[2]);
        arys2 = checkEndDate.split('-');
        var edate = new Date(arys2[0], parseInt(arys2[1] - 1), arys2[2]);
        if (sdate >= edate) {//日期开始时间大于结束时间
            return false;
        } else {
            return true;
        }
    }
}

//判断日期时间大小
function compareTime(startDate, endDate) {
    if (startDate.length > 0 && endDate.length > 0) {
        var startDateTemp = startDate.split(" ");
        var endDateTemp = endDate.split(" ");

        var arrStartDate = startDateTemp[0].split("-");
        var arrEndDate = endDateTemp[0].split("-");

        var arrStartTime = startDateTemp[1].split(":");
        var arrEndTime = endDateTemp[1].split(":");

        var allStartDate = new Date(arrStartDate[0], arrStartDate[1], arrStartDate[2], arrStartTime[0], arrStartTime[1], arrStartTime[2]);
        var allEndDate = new Date(arrEndDate[0], arrEndDate[1], arrEndDate[2], arrEndTime[0], arrEndTime[1], arrEndTime[2]);

        if (allStartDate.getTime() >= allEndDate.getTime()) {//startTime不能大于endTime，不能通过
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

//比较日期，时间大小
function compareCalendar(startDate, endDate) {
    if (startDate.indexOf(" ") != -1 && endDate.indexOf(" ") != -1) {
        compareTime(startDate, endDate);
    } else {
        compareDate(startDate, endDate);
    }
}


/*--------------------------------判断是否存在指定变量 -----------------------------------------*/
function isExitsParamsVariable(variableName) {
    try {
        console.log("variableName.length===" + variableName.length);
        if (variableName.length == 0) {
            console.log(variableName + "===value has no params");//""：length为0
            return false;
        } else {
            console.log(variableName + "======value has params");//0:length为undefined
            return true;
        }
    } catch (e) {
        console.log(variableName + "----我异常了!!!!!!!!");//null,undefined,未赋值的a
    }
    return false;//null,undefined,未赋值的a
}

/*---------------------------------判断是否undefined--------------------------------*/
function isExitsVariable(variableName) {
    console.log("typeof variableName====" + typeof (variableName));
    try {
        if (typeof (variableName) == "undefined") {
            console.log(variableName + "===value is undefined");//undefined,未赋值的a
            return false;
        } else {
            console.log(variableName + "=======value is true");//null,0,""
            return true;
        }
    } catch (e) {
        console.log(variableName + "-------我异常了........");
    }
    return false;
}

/**
 * 将字符转日期格式化成2015-12-14 22:34:56
 * @param 20151214223456
 */
function stringFormDate(dateStr) {
    if (isEmpty(dateStr)) return "";
    return dateStr.substr(0, 4) + "-" + dateStr.substr(4, 2) + "-" + dateStr.substr(6, 2) + " " + dateStr.substr(8, 2) + ":" + dateStr.substr(10, 2) + ":" + dateStr.substr(12, 2);
}

/**
 * 去除OBJ对象中所有字符串前后空格
 * @param obj
 */
function trimObject(jsonObj) {
    if (isEmpty(jsonObj)) return null;
    for (var names in jsonObj) {
        if (isNotEmpt(jsonObj[names])) {
            jsonObj[names] = ITS.trim(jsonObj[names]);
        }
    }
    return jsonObj;
}

//全局对象
var ITS = {};

ITS.apply = function (target, source) {
    for (r in source) {
        target[r] = source[r];
    }
}


ITS.extend = function (o, n, override) {
    for (var p in n) if (n.hasOwnProperty(p) && (!o.hasOwnProperty(p) || override)) o[p] = n[p];
};

ITS.trim = function (obj) {
    if (undefined == obj || obj.length == 0 || null == obj)
        return false;
    else {
        var result = " " + obj;
        return result.replace(/(^\s*)|(\s*$)/g, '');
    }
};

var Utils = {};

Utils.systemType = {
    SYS: "sys",
    PARK: "park"
};

/**
 * 创建下拉列表
 * @param json
 */
Utils.createDataDictDropDownList = function (json, that, callback, sysType) {
    var parentModelKey = "";
    var jsonArray = json;
    if (null != json && json.constructor == Object) {
        if (null == dataDictMapList.get(json["parentModelKey"])) {
            parentModelKey = json["parentModelKey"] + SEPARATOR;
        }
        jsonArray = new Array();
        jsonArray.push(json);
    } else {
        for (var i = 0; i < json.length; i++) {
            if (null == dataDictMapList.get(json[i]["parentModelKey"])) {
                parentModelKey += json[i]["parentModelKey"] + SEPARATOR;
            }
        }
    }
    if ("" != parentModelKey) {  //字典未被缓存则从后台抽取
        parentModelKey = parentModelKey.substring(0, parentModelKey.length - 1);
        this.remoteGetDataDict(parentModelKey, sysType);
    }
    //全部被缓存，从缓存直接抽取
    this.fullDataDictDropDowmList(jsonArray, that, callback);
};
/**
 * 非字典数据填充下拉列表
 */
Utils.createAjaxDropDownList = function (json, that, callback) {
    var dataSource = json["select"];
    if (json["unshift"]) {
        dataSource.unshift({name: "--请选择--", code: ""});
    }
    var dropDownList = json["div"].kendoDropDownList({
        dataTextField: "name",
        dataValueField: "code",
        dataSource: dataSource
    }).data("kendoDropDownList");
    if (null != json["dataBound"] && typeof json["dataBound"] == "function") {
        dropDownList.bind("dataBound", json["dataBound"]);
    }
    if (null != json["change"] && typeof json["change"] == "function") {
        dropDownList.bind("change", json["change"]);
    }
    /*if(isNotEmpt(json["select"])){
        var dataBind = $(json["div"]).attr("data-bind").split(":")[1];
        var bind = dataBind[dataBind.length-1];
        that.sysUtils.mvvmModel.set(dataBind.replace(","),json["select"]);
    }else{
        dropDownList.select(0);
    }*/
    //回调最外层函数
    if (null != callback && typeof callback == "function") {
        callback.apply(that);
    }
}
/**
 * 服务器上获取数据字典信息
 */
Utils.remoteGetDataDict = function (parentModelKey, systemType) {
    var that = this;
    let url = baseApiPath + "basSystemDataDict/findDataDictListByParentKey/" + parentModelKey;
    if (isEmpty(systemType)) {
        systemType = this.systemType.PARK; //默认查停车场
    }
    // if (this.systemType.SYS == systemType) {
    //系统数据字典
    JsonpAjax(url, null, function (result) {
        if (0 === result.code)
            that.cacheDataDict(result.data);
    },"GET");

    // } else if (this.systemType.PARK == systemType) {  //停车场数据字典
    //     JsonpAjax(baseApiPath + "basSystemDataDict/findDataDictListByParentKey?" + parentModelKey, "", "json", function (result) {
    //         that.cacheDataDict(result);
    //     }, false);
    // }
}

/**
 * 填充下拉列表值
 */
Utils.fullDataDictDropDowmList = function (jsonArray, that, callback) {
    for (var i = 0; i < jsonArray.length; i++) {
        var dataSource = jQuery.extend(true, [{}], dataDictMapList.get(jsonArray[i]["parentModelKey"]));
        if (jsonArray[i]["unshift"] != true) {  //unshift 不等于true 表示要带请选择
            dataSource.unshift({modelName: "--请选择--", modelValue: ""});
        }
        var dropDownList = jsonArray[i]["div"].kendoDropDownList({
            dataTextField: "modelName",
            dataValueField: "modelValue",
            dataSource: dataSource
        }).data("kendoDropDownList");
        if (null != jsonArray[i]["dataBound"] && typeof jsonArray[i]["dataBound"] == "function") {
            dropDownList.bind("dataBound", jsonArray[i]["dataBound"]);
        }
        if (null != jsonArray[i]["change"] && typeof jsonArray[i]["change"] == "function") {
            dropDownList.bind("change", jsonArray[i]["change"]);
        }
        if (isNotEmpt(jsonArray[i]["select"])) {
            var dataBind = $(jsonArray[i]["div"]).attr("data-bind");
            if (isNotEmpt(dataBind)) {
                dataBind = dataBind.split(":")[1];
                that.sysUtils.mvvmModel.set(dataBind.replace(","), jsonArray[i]["select"]);
            } else {
                // for(var t = 0 ;t<dataSource.length;t++) {
                // 	if (dataSource[t]["modelValue"] == jsonArray[i]["select"]) {
                // 		dropDownList.select(t);
                // 	}
                // }
                dropDownList.value(jsonArray[i]["select"]);
            }
        } else {
            dropDownList.select(0);
        }
    }
    //回调最外层函数
    if (null != callback && typeof callback == "function") {
        callback.apply(that);
    }
};
/**
 * 缓存数据字典
 * @param mapResult
 */
Utils.cacheDataDict = function (mapResult) {
    for (var names in mapResult) {
        dataDictMapList.put(names, mapResult[names]);
        for (var i = 0; i < mapResult[names].length; i++) {
            dataDictMap.put(mapResult[names][i]["modelKey"], mapResult[names][i]);
        }
    }
};

/**
 * 查询对应的字典名称
 */
Utils.getModelNameByParentKey = function (parentKey, val, sysType) {
    var dataDictList = dataDictMapList.get(parentKey);
    if (null == dataDictList) {  //缓存中没找到，从系统后台找
        this.remoteGetDataDict(parentKey, sysType);
    }
    dataDictList = dataDictMapList.get(parentKey);
    if (null == dataDictList) return "异常";
    for (var i = 0; i < dataDictList.length; i++) {
        if (val == dataDictList[i]["modelValue"]) {
            return dataDictList[i]["modelName"];
        }
    }
    return "无";
};

/**
 * 查询对应的字典值
 */
Utils.getModelValueByModelKey = function (modelKey, sysType) {
    var dataDict = dataDictMap.get(modelKey);
    if (null == dataDict) {
        var that = this;
        var url = baseApiPath + "parkDataDict/findDataDictByModelKey";
        if (this.systemType.SYS == sysType) {
            url = baseApiPath + "findDataDictByModelKey";
        }
        JsonpAjax(url + "?modelKey=" + modelKey, "", "json", function (result) {
            dataDictMap.put(modelKey, result);
            var dataDictList = dataDictMapList.get(result["parentModelKey"]);
            if (null != dataDictList) {
                dataDictList.push(result);
                dataDictMapList.put(result["parentModelKey"], dataDictList);
            }
            dataDict = result;
        }, false);
    }
    return dataDict["modelValue"];
}

/**
 * 查询对应的字典值
 */
Utils.getModelArrayByParentModelKey = function (parentModelKey, sysType) {
    var dataDictList = dataDictMapList.get(parentModelKey);
    if (null == dataDictList) {
        this.remoteGetDataDict(parentModelKey, sysType);
        return dataDictMapList.get(parentModelKey);
    }
    return dataDictList;
}

/**
 * 查询对应的字典对象
 */
Utils.getDataDictByModelKey = function (modelKey, sysType) {
    var dataDict = dataDictMap.get(modelKey);
    if (null == dataDict) {
        var that = this;
        var url = baseApiPath + "parkDataDict/findDataDictByModelKey";
        if (this.systemType.SYS == sysType) {
            url = baseApiPath + "findDataDictByModelKey";
        }
        JsonpAjax(url + "?modelKey=" + modelKey, "", "json", function (result) {
            dataDictMap.put(modelKey, result);
            var dataDictList = dataDictMapList.get(result["parentModelKey"]);
            if (null != dataDictList) {
                dataDictList.push(result);
                dataDictMapList.put(result["parentModelKey"], dataDictList);
            }
            dataDict = result;
        }, false);
    }
    return dataDict;
}

/**
 * 补足相应长度的位数
 */
Utils.complementDigit = function (string, length) {
    string = string + "";
    for (var i = string.length; i < length; i++) {
        string = "0" + string;
    }
    return string;
}

/**
 * 设置特殊页面session永不失效
 * @param targetObj
 */
Utils.keepsession = function () {
    document.all["Back"].src = "/views/parkLotCenter/common/session_keep.html?RandStr=" + Math.random();
    window.setTimeout("Utils.keepsession()", 900000); //每隔900秒调用一下本身
}

/**
 * 轮循替换code对应显示值
 * @param oldStr
 * @param type
 * @param key
 * @returns {*}
 */
Utils.autoReplace = function (oldStr, type, key) {
    if (type == 'SPEECH_TYPE') {
        $(Utils.getModelArrayByParentModelKey(BASIS.MODEL_DATA_TYPE.ROOT)).each(function (index) {
            if (oldStr) {
                oldStr = oldStr.replace(new RegExp("\\{" + index + "\\}", "g"), '[' + this.modelName + ']');
            }
        });

    } else if (type == 'DISPLAY_CONTENT') {
        $(Utils.getModelArrayByParentModelKey(BASIS.DISPLAY_CONTENT.ROOT)).each(function (index) {
            if (this.modelKey == key && oldStr.indexOf('%s') != -1) {
                if (oldStr) {
                    oldStr = oldStr.replaceAll('%s', '[' + this.modelName + ']');
                }
                return oldStr;
            }
        });
    }
    return oldStr;
}

/**
 * 将时间戳差值转换为日期格式数据
 * @param msd
 * @returns {number}
 * @constructor
 */
Utils.MillisecondToDate = function (msd) {
    var time = parseFloat(msd) / 1000;
    if (null != time && "" != time) {
        if (time > 60 && time < 60 * 60) {
            time = parseInt(time / 60.0) + "分钟" + parseInt((parseFloat(time / 60.0) -
                parseInt(time / 60.0)) * 60) + "秒";
        } else if (time >= 60 * 60 && time < 60 * 60 * 24) {
            time = parseInt(time / 3600.0) + "小时" + parseInt((parseFloat(time / 3600.0) -
                parseInt(time / 3600.0)) * 60) + "分钟" +
                parseInt((parseFloat((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60) -
                    parseInt((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60)) * 60) + "秒";
        } else {
            time = parseInt(time) + "秒";
        }
    } else {
        time = "0 时 0 分0 秒";
    }
    return time;
}